#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.http.response import HttpResponse
from rest_framework import response, status, permissions
from rest_framework.decorators import api_view, permission_classes

from unitool.slib.wx_sdk import ( 
    Common_util_pub, Wxpay_server_pub, NotifyGZHPub, MsgReturn, QingHuaService
)

@permission_classes((permissions.AllowAny,))
@api_view(["GET", "POST"])
def weixin_token(request):
    # /tool/wxtoken?signature=ec98c7a23b10ea3d636cde425d128c2a57647cf0&echostr=3340257735368761341&timestamp=1591892357&nonce=730610766
    '''
    请求字符串 用 & 分割。第一部分是action ， 第二部分开始分别是请求参数 
    '''
    if request.method == "GET":
        instance = NotifyGZHPub(request.query_params)
        if not instance.checkSign():
             print('验证不通过')
        print(request.query_params)
        print(request.data)
        return HttpResponse(request.query_params['echostr'])
    elif request.method == "POST":
        instance = MsgReturn(request.body.decode())
        if not instance.checkSign(request.query_params):
            return HttpResponse('签名验证失败')
        msg = instance.getData().get('Content', 'help').split('&')
        config = {
            "help": "我是今天的值班GM 妲己，请问主人有什么需要帮助的呢？",
        }
        res = config.get(msg[0].strip(), None)
        if not res:
            res = config.get('help')
        else:
            try:
                res = eval(res)
            except Exception:
                pass

        if msg[0].strip() == 'article':
            if msg[1].strip() == 'page':
                res = requests.get('http://tool.gmclqb.cn/tool/article/?page=%s'% msg[2].strip()).json()
                res = "共 {count} 篇\n当前 {page} 页\n{result}".format(count=res['count'], page=msg[2], result='\n'.join(res['results']))
            else:
                res = requests.get('http://tool.gmclqb.cn/tool/article/%s'% msg[1].strip()).json()
                res = res['res']
        else:
            # 土味情话服务
            mode = {
                "我爱你": 3,
                "爱死你了": 4,
                "伤心": 5,
                "好无聊": 2
            }
            res = QingHuaService(mode=mode.get(msg[0], 1)).qh_msg
        return HttpResponse(instance.returnXml(res))


